import sys
import os
import logging
import re
import json
from typing import Dict, List, Any, Optional, Tuple

# 添加项目根路径到 sys.path
sys.path.append(os.path.join(os.path.dirname(os.path.abspath(__file__)), '..', '..'))

# 导入 MySQLUtil
from shared.utils.MySQLUtil import MySQLUtil

# 设置日志
logger = logging.getLogger(__name__)

def get_各学历及总体_就业行业分布(
    project_id: int,
    questionnaire_ids: List[int],
    product_code: Optional[str] = None,
    project_code: Optional[str] = None,
    region_code: Optional[str] = None,
    education: Optional[str] = None
) -> Dict[str, Any]:
    """
    各学历及总体，就业行业分布 - 指标计算函数
    
    ## 指标说明
    计算各学历层次及总体毕业生的就业行业分布情况，统计各行业门类的就业人数及其占比。
    指标限定毕业去向不为待就业和暂不就业，且行业门类字段不为空。
    可以按学历筛选（本科毕业生、专科毕业生、硕士研究生、博士研究生），也可以计算总体数据。
    
    ## Args
        project_id (int): 项目ID，用于查询项目配置信息
        questionnaire_ids (List[int]): 问卷ID集合，用于确定数据范围
        product_code (Optional[str]): 产品编码，用于路由到特定计算逻辑
        project_code (Optional[str]): 项目编码，用于路由到特定计算逻辑
        region_code (Optional[str]): 区域编码，用于路由到特定计算逻辑
        education (Optional[str]): 学历筛选条件，可选值：本科毕业生、专科毕业生、硕士研究生、博士研究生
    
    ## 示例
    ### 输入
    ```json
    {
        "project_id": 5895,
        "questionnaire_ids": [11158, 11159]
    }
    ```
    
    ### 输出
    ```json
    {
        "success": true,
        "message": "ok",
        "code": 0,
        "result": [
            {
                "group": "本科毕业生",
                "data": [
                    {
                        "industry": "制造业",
                        "count": 1200,
                        "ratio": 0.25
                    },
                    {
                        "industry": "信息传输、软件和信息技术服务业",
                        "count": 800,
                        "ratio": 0.1667
                    }
                ]
            },
            {
                "group": "总体",
                "data": [
                    {
                        "industry": "制造业",
                        "count": 3000,
                        "ratio": 0.3
                    },
                    {
                        "industry": "教育",
                        "count": 1800,
                        "ratio": 0.18
                    }
                ]
            }
        ]
    }
    ```
    """
    logger.info(f"开始计算指标: 各学历及总体，就业行业分布, 项目ID: {project_id}")
    
    try:
        db = MySQLUtil()  

        # 1. 查询项目配置信息
        project_sql = """
        SELECT client_code, item_year, split_tb_paper 
        FROM client_item 
        WHERE id = %s
        """
        project_info = db.fetchone(project_sql, (project_id,))
        if not project_info:
            raise ValueError(f"未找到项目ID={project_id}的配置信息")

        client_code = project_info['client_code']
        item_year = project_info['item_year']
        
        logger.info(f"项目配置: client_code={client_code}, item_year={item_year}")

        # 2. 计算 shard_tb_key（去除前缀字母和前导0）
        shard_tb_key = re.sub(r'^[A-Za-z]*0*', '', client_code)
        logger.info(f"计算得到 shard_tb_key: {shard_tb_key}")

        # 3. 构建表名
        student_table = f"dim_client_target_baseinfo_student_calc_{item_year}"
        
        # 4. 处理学历参数（空字符串转为None）
        if education == '':
            education = None
        
        # 5. 构建学历筛选条件
        education_condition = ""
        if education:
            if education not in ["本科毕业生", "专科毕业生", "硕士研究生", "博士研究生"]:
                raise ValueError(f"学历参数错误，必须是: 本科毕业生、专科毕业生、硕士研究生、博士研究生")
            education_condition = f"AND education = '{education}'"
        
        logger.info(f"学历筛选: {education if education else '不限制'}")

        # 6. 查询各行业就业人数及占比
        def query_industry_distribution(edu_condition: str, group_name: str) -> Dict[str, Any]:
            """查询行业分布数据"""
            sql = f"""
            SELECT 
                indus_class_object as industry,
                count(*) as count,
                count(*)/(
                    SELECT count(*) 
                    FROM {student_table} 
                    WHERE shard_tb_key = %s 
                    AND grad_dest_merge != '待就业' 
                    AND grad_dest_merge != '暂不就业' 
                    AND indus_class_object != '' 
                    {edu_condition}
                ) AS ratio
            FROM {student_table}
            WHERE 
                shard_tb_key = %s
                AND grad_dest_merge != '待就业'
                AND grad_dest_merge != '暂不就业'
                AND indus_class_object != ''
                {edu_condition}
            GROUP BY indus_class_object
            ORDER BY ratio DESC
            """
            results = db.fetchall(sql, (shard_tb_key, shard_tb_key))
            
            # 记录查询结果统计
            total_count = sum([row["count"] for row in results]) if results else 0
            logger.info(f"分组 '{group_name}': 查询到 {len(results)} 个行业，总就业人数={total_count}")
            if results:
                top3 = results[:3]
                logger.info(f"  前3个行业: {[(r['industry'], r['count']) for r in top3]}")
            
            return {
                "group": group_name,
                "data": [
                    {
                        "industry": row["industry"],
                        "count": int(row["count"]),
                        "ratio": round(float(row["ratio"]), 4)  # 保留4位小数
                    } for row in results
                ]
            }

        # 7. 计算各学历和总体数据
        result = []
        
        # 7.1 如果指定了学历，只返回该学历的数据
        if education:
            logger.info(f"开始计算学历 '{education}' 的行业分布")
            result.append(query_industry_distribution(f"AND education = '{education}'", education))
        else:
            # 7.2 如果没有指定学历，返回所有学历的明细数据
            logger.info("开始计算所有学历的行业分布明细")
            education_list = ["本科毕业生", "专科毕业生", "硕士研究生", "博士研究生"]
            
            for edu in education_list:
                logger.info(f"计算学历 '{edu}' 的行业分布")
                edu_data = query_industry_distribution(f"AND education = '{edu}'", edu)
                # 只添加有数据的学历
                if edu_data['data']:
                    result.append(edu_data)
        
        # 7.3 计算总体数据（必须包含）
        logger.info("开始计算总体行业分布")
        result.append(query_industry_distribution("", "总体"))

        logger.info(f"指标 '各学历及总体，就业行业分布' 计算成功")
        return {
            "success": True,
            "message": "ok",
            "code": 0,
            "result": result
        }

    except Exception as e:
        logger.error(f"计算指标 '各学历及总体，就业行业分布' 时发生错误: {str(e)}", exc_info=True)
        return {
            "success": False,
            "message": f"数据获取失败: 各学历及总体，就业行业分布",
            "code": 500,
            "error": str(e)
        }